<template>
  <view class="search-bar" :class="searchBarClass">
    <!-- 搜索输入框 -->
    <view class="search-input-container">
      <uni-icons type="search" size="18" color="#999999" class="search-icon" />
      <input
        class="search-input"
        v-model="searchValue"
        :placeholder="placeholder"
        :placeholder-style="placeholderStyle"
        :maxlength="maxlength"
        :focus="autoFocus"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        @confirm="handleSearch"
      />
      <!-- 清除按钮 -->
      <view
        class="clear-btn"
        v-if="searchValue && showClear"
        @click="handleClear"
      >
        <uni-icons type="clear" size="16" color="#CCCCCC" />
      </view>
    </view>

    <!-- 搜索按钮 -->
    <view class="search-btn" v-if="showSearchBtn" @click="handleSearch">
      <text class="search-btn-text">{{ searchBtnText }}</text>
    </view>

    <!-- 语音搜索按钮 -->
    <view class="voice-btn" v-if="showVoice" @click="handleVoiceSearch">
      <uni-icons type="mic" size="20" color="#666666" />
    </view>

    <!-- 扫码搜索按钮 -->
    <view class="scan-btn" v-if="showScan" @click="handleScanSearch">
      <uni-icons type="scan" size="20" color="#666666" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";

// Props 定义
interface Props {
  // 基础配置
  modelValue?: string;
  placeholder?: string;
  maxlength?: number;
  autoFocus?: boolean;

  // 样式配置
  shape?: "round" | "square";
  size?: "small" | "medium" | "large";
  background?: string;
  borderColor?: string;

  // 功能配置
  showClear?: boolean;
  showSearchBtn?: boolean;
  showVoice?: boolean;
  showScan?: boolean;
  searchBtnText?: string;

  // 行为配置
  searchOnInput?: boolean;
  debounceTime?: number;
  disabled?: boolean;
  readonly?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  placeholder: "搜索商品",
  maxlength: 50,
  autoFocus: false,
  shape: "round",
  size: "medium",
  background: "#F5F5F5",
  borderColor: "",
  showClear: true,
  showSearchBtn: false,
  showVoice: false,
  showScan: false,
  searchBtnText: "搜索",
  searchOnInput: false,
  debounceTime: 300,
  disabled: false,
  readonly: false,
});

// Emits 定义
interface Emits {
  "update:modelValue": [value: string];
  search: [value: string];
  input: [value: string];
  focus: [];
  blur: [];
  clear: [];
  voice: [];
  scan: [];
}

const emit = defineEmits<Emits>();

// 搜索值
const searchValue = ref(props.modelValue);

// 是否聚焦
const isFocused = ref(false);

// 防抖定时器
let debounceTimer: number | null = null;

// 监听外部值变化
watch(
  () => props.modelValue,
  (newValue) => {
    searchValue.value = newValue;
  }
);

// 监听内部值变化
watch(searchValue, (newValue) => {
  emit("update:modelValue", newValue);
});

// 搜索框样式类
const searchBarClass = computed(() => {
  return {
    [`shape-${props.shape}`]: true,
    [`size-${props.size}`]: true,
    focused: isFocused.value,
    disabled: props.disabled,
    readonly: props.readonly,
  };
});

// 占位符样式
const placeholderStyle = computed(() => {
  return "color: #CCCCCC; font-size: 28rpx;";
});

// 处理输入
const handleInput = (e: any) => {
  const value = e.detail.value;
  searchValue.value = value;
  emit("input", value);

  // 实时搜索
  if (props.searchOnInput) {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
      emit("search", value);
    }, props.debounceTime);
  }
};

// 处理聚焦
const handleFocus = () => {
  isFocused.value = true;
  emit("focus");
};

// 处理失焦
const handleBlur = () => {
  isFocused.value = false;
  emit("blur");
};

// 处理搜索
const handleSearch = () => {
  if (props.disabled || props.readonly) return;

  const value = searchValue.value.trim();
  emit("search", value);

  // 收起键盘
  uni.hideKeyboard();
};

// 处理清除
const handleClear = () => {
  if (props.disabled || props.readonly) return;

  searchValue.value = "";
  emit("clear");
  emit("update:modelValue", "");
};

// 处理语音搜索
const handleVoiceSearch = () => {
  if (props.disabled) return;

  emit("voice");

  // TODO: 实现语音搜索功能
  uni.showToast({
    title: "语音搜索功能开发中",
    icon: "none",
  });
};

// 处理扫码搜索
const handleScanSearch = () => {
  if (props.disabled) return;

  emit("scan");

  // 扫码搜索
  uni.scanCode({
    success: (res) => {
      const result = res.result;
      searchValue.value = result;
      emit("search", result);
    },
    fail: (error) => {
      console.error("扫码失败:", error);
      uni.showToast({
        title: "扫码失败",
        icon: "none",
      });
    },
  });
};

// 暴露方法
defineExpose({
  focus: () => {
    // TODO: 聚焦输入框
  },
  blur: () => {
    // TODO: 失焦输入框
  },
  clear: handleClear,
});
</script>

<style lang="scss" scoped>
.search-bar {
  display: flex;
  align-items: center;
  gap: 20rpx;
  transition: all 0.3s ease;

  &.disabled {
    opacity: 0.6;
    pointer-events: none;
  }

  &.readonly {
    .search-input {
      color: #999999;
    }
  }

  // 尺寸变体
  &.size-small {
    .search-input-container {
      height: 60rpx;
      padding: 0 20rpx;
    }

    .search-input {
      font-size: 24rpx;
    }

    .search-btn {
      height: 60rpx;
      padding: 0 20rpx;
    }

    .search-btn-text {
      font-size: 24rpx;
    }
  }

  &.size-medium {
    .search-input-container {
      height: 70rpx;
      padding: 0 25rpx;
    }

    .search-input {
      font-size: 28rpx;
    }

    .search-btn {
      height: 70rpx;
      padding: 0 25rpx;
    }

    .search-btn-text {
      font-size: 28rpx;
    }
  }

  &.size-large {
    .search-input-container {
      height: 80rpx;
      padding: 0 30rpx;
    }

    .search-input {
      font-size: 32rpx;
    }

    .search-btn {
      height: 80rpx;
      padding: 0 30rpx;
    }

    .search-btn-text {
      font-size: 32rpx;
    }
  }

  // 形状变体
  &.shape-round {
    .search-input-container,
    .search-btn {
      border-radius: 50rpx;
    }
  }

  &.shape-square {
    .search-input-container,
    .search-btn {
      border-radius: 12rpx;
    }
  }

  // 聚焦状态
  &.focused {
    .search-input-container {
      border-color: #07c160;
      box-shadow: 0 0 0 4rpx rgba(7, 193, 96, 0.1);
    }
  }
}

.search-input-container {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: var(--search-bg, #f5f5f5);
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
  position: relative;
}

.search-icon {
  margin-right: 15rpx;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  height: 100%;
  border: none;
  outline: none;
  background: transparent;
  color: #333333;
  min-height: 0;
}

.clear-btn {
  margin-left: 15rpx;
  padding: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: opacity 0.2s ease;

  &:active {
    opacity: 0.6;
  }
}

.search-btn {
  background-color: #07c160;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  flex-shrink: 0;

  &:active {
    background-color: #05a050;
    transform: scale(0.98);
  }
}

.search-btn-text {
  font-weight: 500;
}

.voice-btn,
.scan-btn {
  width: 70rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border: 2rpx solid #eeeeee;
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.2s ease;
  flex-shrink: 0;

  &:active {
    background-color: #f8f8f8;
    transform: scale(0.95);
  }
}

// 动画效果
@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-5rpx);
  }
  75% {
    transform: translateX(5rpx);
  }
}

.search-bar.error {
  .search-input-container {
    border-color: #ff4444;
    animation: shake 0.5s ease-in-out;
  }
}

// 响应式适配
@media screen and (max-width: 750rpx) {
  .search-bar {
    gap: 15rpx;

    &.size-large {
      .search-input-container {
        height: 70rpx;
      }

      .search-btn {
        height: 70rpx;
      }
    }
  }

  .voice-btn,
  .scan-btn {
    width: 60rpx;
    height: 60rpx;
  }
}
</style>
